import { Button, Checkbox, Col, Form, Input, message, Row, Upload } from 'antd';
import '@/components/BaseForm/antdform.less';
import { baseFormConfig } from '@/components/BaseForm/config';
import Demo from './tree';
import { useRef, useState } from 'react';
import { request } from 'umi';
import * as XLSX from 'xlsx';
import { CloudUploadOutlined, MinusCircleOutlined } from '@ant-design/icons';
import './style.less';

const CheckedStyle = {
  color: 'rgba(23, 117, 245, 1)',
  border: '1px solid rgba(23, 117, 245, 1)',
};
const UnCheckedStyle = {
  color: 'black',
  border: '1px solid rgba(216, 224, 240, 1)',
};
const onFinish = (values: any) => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
type UserInfoType = {
  handleClose?: () => void;
  role: number;
};

const DownloadExcel = async () => {
  try {
    const api = 'http://localhost:8080/api/excel/download';
    const response = await request(api, {
      method: 'GET',
      responseType: 'blob',
    });

    // 创建URL以下载文件
    const blob = new Blob([response], { type: 'application/octet-stream' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'filename.xlsx';
    link.click();

    // 释放URL
    URL.revokeObjectURL(url);
  } catch (error) {
    console.error(error);
  }
};

const { Group } = Checkbox;

const gradeOptions = [
  { label: '一年级', value: '1' },
  { label: '二年级', value: '2' },
  { label: '三年级', value: '3' },
];

const classOptions = {
  1: [
    { label: '1班', value: '11' },
    { label: '2班', value: '12' },
    { label: '3班', value: '13' },
  ],
  2: [
    { label: '1班', value: '21' },
    { label: '2班', value: '22' },
    { label: '3班', value: '23' },
    { label: '4班', value: '24' },
  ],
  3: [
    { label: '1班', value: '31' },
    { label: '2班', value: '32' },
    { label: '3班', value: '33' },
    { label: '4班', value: '33' },
    { label: '5班', value: '35' },
  ],
};

const ClassCheckBoxGrounp = () => {
  const [gradeIndex, setGradeIndex] = useState(0);
  const [grades, setGrades] = useState([
    { name: '一年级', checked: false },
    { name: '二年级', checked: false },
    { name: '三年级', checked: false },
  ]);
  const [selectedClasses, setSelectedClasses] = useState([]);

  const handleCheck = (index: number) => {
    setGradeIndex(index);
    const newGrades = [...grades];
    newGrades[index].checked = !newGrades[index].checked;
    setGrades(newGrades);
  };

  const handleClassChange = (selected: any) => {
    setSelectedClasses(selected);
  };
  return (
    <div>
      <div className="customCheckBoxGroup">
        {grades.map((grade, index) => (
          <div
            key={index}
            className="customCheckBox"
            style={grades[index].checked ? CheckedStyle : UnCheckedStyle}
          >
            <label>
              {grade.name}
              <input type="checkbox" checked={grade.checked} onChange={() => handleCheck(index)} />
            </label>
          </div>
        ))}
      </div>

      {grades[gradeIndex].checked && (
        <div className="childCheckBoxGroup">
          <Checkbox.Group
            options={classOptions[gradeIndex + 1]}
            value={selectedClasses}
            onChange={handleClassChange}
          />
        </div>
      )}
    </div>
  );
};

const UserInfo = (props: UserInfoType) => {
  const [fileList, setFileList] = useState<any>([]);
  const { handleClose, role } = props;
  const formRef = useRef<any>(null);
  const [stepValue, setStepValue] = useState('first');
  const [uploadedCount, setUploadedCount] = useState(0);

  const handleFileChange = (info: { fileList: string | any[] }) => {
    setUploadedCount(info.fileList.length);
    console.log('uploadedCount', uploadedCount);
  };
  // console.log("props", props);

  const onFirstStepFinish = (values: any) => {
    console.log('Success:', values);
    formRef.current
      .validateFields()
      .then(() => {
        // 遍历所有表单项，判断是否填写完毕
        const hasError = Object.keys(formRef.current.getFieldsError()).some((field) => {
          return formRef.current.isFieldTouched(field) && formRef.current.getFieldError(field);
        });
        if (hasError) {
          // 表单验证失败，展示错误信息
        } else {
          // 表单验证成功，可以提交表单
          setStepValue('second');
        }
      })
      .catch((error: any) => {
        // 表单验证失败，展示错误信息
        console.log(error);
      });
  };

  // 处理上传文件
  const handleUpload = async () => {
    const formData = new FormData();
    formData.append('file', fileList);
    try {
      const response = await request('http://localhost:8080/api/excel/upload', {
        method: 'POST',
        body: formData,
      });
      message.success(response || '');
      setFileList([]);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  const handleUserInfoClose = () => {
    console.log(111);
    handleUpload();
    return handleClose!();
  };
  const handleBeforeUpload = (file: any) => {
    const allowType = [
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ];
    const isExcel = allowType.includes(file.type);

    if (!isExcel) {
      message.error('只能上传 Excel 文件！');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('文件大小不能超过 2MB！');
      return false;
    }
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = () => {
      const workbook = XLSX.read(reader.result, { type: 'binary' });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const data = XLSX.utils.sheet_to_json(worksheet);
      console.log(data);
    };
    setFileList(file);
  };

  const UploadProps = {
    accept: '.xls,.xlsx',
    beforeUpload: handleBeforeUpload,
    onChange: handleFileChange,
    showUploadList: {
      // showDownloadIcon: true,
      // downloadIcon: "Download",
      showRemoveIcon: true,
      removeIcon: (
        <MinusCircleOutlined onClick={(e) => console.log(e, 'custom removeIcon event')} />
      ),
    },
  };

  return (
    <>
      {stepValue === 'first' && (
        <Form
          {...baseFormConfig}
          ref={formRef}
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          {role === 1 && (
            <>
              <div className="form-title">管理员信息</div>
              <Form.Item
                label="管理员姓名"
                name="title"
                rules={[{ required: true, message: '请输入标题!' }]}
              >
                <Input placeholder="输入管理员姓名" />
              </Form.Item>
              <div className="form-title">校园信息</div>
              <Form.Item
                label="学校名称"
                name="schoolname"
                rules={[{ required: true, message: '请输入学科!' }]}
              >
                <Input placeholder="请输入校园名称" />
              </Form.Item>
              <Form.Item
                label="学校地址"
                name="address"
                rules={[{ required: true, message: '请输入学校地址!' }]}
              >
                <Input placeholder="学校地址" />
              </Form.Item>
              <Form.Item
                label="简介"
                name="content"
                rules={[{ required: true, message: '请输入简介!' }]}
              >
                <Input placeholder="添加一些描述" />
              </Form.Item>
              <Form.Item
                label="组织架构"
                name="demo"
                // rules={[{ required: true, message: "请输入学科!" }]}
              >
                <Demo />
              </Form.Item>
            </>
          )}
          {role === 3 && (
            <>
              <div className="form-title">老师信息</div>
              <Form.Item
                label="姓名"
                name="title"
                rules={[{ required: true, message: '请输入姓名!' }]}
              >
                <Input placeholder="输入姓名" />
              </Form.Item>
              <Form.Item
                label="手机号"
                name="title"
                rules={[{ required: true, message: '请输入手机号!' }]}
              >
                <Input placeholder="输入手机号" />
              </Form.Item>
              <div className="form-title">校园信息</div>
              <Form.Item
                label="学校名称"
                name="schoolname"
                rules={[{ required: true, message: '请输入校园名称!' }]}
              >
                <Input placeholder="请输入校园名称" />
              </Form.Item>
              <Form.Item
                label="学校地址"
                name="address"
                rules={[{ required: true, message: '请输入学校地址!' }]}
              >
                <Input placeholder="学校地址" />
              </Form.Item>
              <Form.Item
                label="身份"
                name="content"
                rules={[{ required: true, message: '请选择身份' }]}
              >
                <Input placeholder="选择身份" />
              </Form.Item>
              <Form.Item
                label="学科"
                name="content"
                rules={[{ required: true, message: '请输入学科!' }]}
              >
                <Input placeholder="输入学科" />
              </Form.Item>
              <Form.Item
                label="所属班级"
                name="class"
                // rules={[{ required: true, message: "请选择所属班级!" }]}
              >
                <ClassCheckBoxGrounp />
              </Form.Item>
              <Form.Item
                label="组织架构"
                name="demo"
                // rules={[{ required: true, message: "请输入学科!" }]}
              >
                <Demo />
              </Form.Item>
            </>
          )}
          {/* <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item> */}
        </Form>
      )}
      {stepValue === 'second' && (
        <>
          <div>导入教师信息</div>
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              width: '100px',
              height: '200px',
              marginTop: '10px',
            }}
          >
            <Button
              key="cancel"
              onClick={DownloadExcel}
              icon={<CloudUploadOutlined />}
              style={{
                marginRight: '10px',
              }}
            >
              下载模版
            </Button>
            <Upload {...UploadProps}>
              <Button icon={<CloudUploadOutlined />}>导入信息</Button>
              {uploadedCount > 0 && (
                <div
                  style={{
                    marginLeft: '-122px',
                    marginTop: '20px',
                  }}
                >
                  附件
                </div>
              )}
            </Upload>
          </div>
        </>
      )}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
      >
        {stepValue === 'first' && (
          <>
            <Button key="cancel" onClick={handleClose}>
              取消
            </Button>
            <Button key="submit" type="primary" onClick={onFirstStepFinish}>
              下一步
            </Button>
          </>
        )}
        {stepValue === 'second' && (
          <>
            <Button key="cancel" onClick={() => setStepValue('first')}>
              上一步
            </Button>
            <Button key="submit" type="primary" onClick={handleUserInfoClose}>
              完成
            </Button>
          </>
        )}
      </div>
    </>
  );
};

export default UserInfo;
